//
//  LTRefreshView.swift
//  WeiBoProject
//
//  Created by MAC on 16/3/5.
//  Copyright © 2016年 LTQ. All rights reserved.
//

import UIKit
import SnapKit

//    分析出三个状态
enum RefreshType: Int{
    //        case 后面没有:
    // 正常的状态
    case Normal = 0
    // 拖拽的状态
    case Pulling = 1
    // 加载状态
    case Loading = 2
}
class LTRefreshView: UIControl {
//  定义一个成员属性
    var scrollView: UIScrollView?

//    记录一下上一个状态
    var oldStatus: RefreshType = .Normal
    
//    定义一个属性，来记录状态，默认的是正常的状态
    var status:RefreshType = .Normal{
        didSet{
            switch status{
                
            case .Normal:print("正常状态")
                messageLabel.text = "下拉刷新"
            case .Pulling:print("下拉状态")
                messageLabel.text = "释放刷新"
            case .Loading:print("加载中。。。")
                messageLabel.text = "加载中。。。"
//                加载的时候显示在Nav下边 修改scrollView?.contentInset
                var inset = scrollView?.contentInset
                inset?.top += 64
                scrollView?.contentInset = inset!
            // 没有触发 ValueChange的事件
            sendActionsForControlEvents(UIControlEvents.ValueChanged)
                print(scrollView?.contentInset)
//                记录一下加载的状态
                oldStatus = .Loading
            }
        }
    }
    
    func endRefreshing(){
//        加载完成
        status  = .Normal
        
        if oldStatus == .Loading{
            var inset = scrollView?.contentInset
            inset?.top -= 64
            scrollView?.contentInset = inset!
//            sendActionsForControlEvents(UIControlEvents.ValueChanged)
            oldStatus = .Normal
            
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.greenColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   func setupUI(){
    
//    需要给下拉出来的View设置大小，给结构体重新复制，需要先拿到结构体
    var frame = self.frame
    frame.size = CGSizeMake(kUIScreenWidth, 44)
    frame.origin.y = -44
    self.frame = frame
    
    
    addSubview(messageLabel)
    addSubview(arrowImageView)
    addSubview(loadingImageView)
//    添加约束
//    水平居中，向右20点 垂直居中
    messageLabel.snp_makeConstraints { (make) -> Void in
        make.centerX.equalTo(self.snp_centerX).offset(20)
        make.centerY.equalTo(self.snp_centerY)
    }
//    垂直居中，右侧和messageLabel的左侧对其
    arrowImageView.snp_makeConstraints { (make) -> Void in
        make.centerY.equalTo(self.snp_centerY)
        make.right.equalTo(messageLabel.snp_left)
        
    }
    loadingImageView.snp_makeConstraints { (make) -> Void in
        make.center.equalTo(arrowImageView.snp_center)
    }
    
    }
    
//    添加KVO
//    我们把 子控件添加到父控件的时候会调用这个方法
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
//        1.先把 newSuperview 转换一下 UISrollView
        scrollView = newSuperview as? UIScrollView
        
//        2.添加监听00
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //         把被观察对象转换成对应的类型 UIScrollView类型
        let scrollView = object as? UIScrollView
        
        
        //        需要在拖拽的过程中去判断状态
        if scrollView!.dragging {
            //        print(scrollView?.contentOffset.y)
            if scrollView?.contentOffset.y < -150{
                //                print("释放刷新")
                status = .Pulling
                
            }else if scrollView?.contentOffset.y < -114 && scrollView?.contentOffset.y > -150{
                //                print("正常状态，下拉刷新")
                status = .Normal
            }
//          松手之后进行下面判断
        }else{
            //                print("加载中")
            //                加载数据的操作应该在松手之后进行
            if scrollView?.contentOffset.y < -150 && status == .Pulling{
                
                status = .Loading
                
                
            }
            
        }
        
    }
    
//    MARK:--懒加载
    /// 提示语
    private lazy var messageLabel: UILabel = {
        
        let label = UILabel()
        label.text = "下拉刷新"
        label.textColor = UIColor.redColor()
        label.font = UIFont.systemFontOfSize(15)
        return label
    }()
    
    ///箭头
    private lazy var arrowImageView: UIImageView = {
       
        let img = UIImageView()
        
        img.image = UIImage(named:"tableview_pull_refresh")
        return img
        
    }()
    
    ///加载的视图
    private lazy var loadingImageView:UIImageView = {
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_loading")
       return img
    }()
    
    
}









